import { BrowserWindow } from 'electron';
import { asset, isDev as isDevelopment } from '../util';
import { format as formatUrl } from 'url';
import cfg from '../renderer/config';
import * as path from 'path';
import * as util from '../util';

// 创建主窗口 (单例模式: 一个类或者函数只允许创建一个实例)
let mainWindow;
export function createMainWindow() {
  if (!mainWindow) {
    const windowFrame = process.env.frame !== undefined ? process.env.frame === '1' : false;
    const mainUrl = isDevelopment
      ? `http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`
      : formatUrl({
          pathname: path.join(__dirname, 'index.html'),
          protocol: 'file',
          slashes: true,
        });
    const iconPath = asset('icon.ico');
    console.log('iconPath ===========> ', iconPath)

    mainWindow = new BrowserWindow({
      // transparent: true,
      frame: windowFrame,
      resizable: true,
      show: false,
      width: 1280,
      height: 800,
      // width: dimensions.width,
      // height: screenHeightWithoutTaskbar,
      minWidth: 1280,
      minHeight: 800,
      icon: iconPath,
      webPreferences: {
        // devTools: true,
        contextIsolation: false,
        enableRemoteModule: true,
        nodeIntegration: true,
        nodeIntegrationInSubFrames: true,
        webviewTag: true,
        contentSecurityPolicy: "default-src 'self'; frame-src *;", // 配置CSP 参数如下
        partition: 'persist:app',
      },
    });

    /*
      default-src 'self': 默认情况下只允许加载来自同一源的资源。
      frame-src *: 允许从任何源加载 iframe。
      connect-src 'self': 允许从同一源发起网络请求。
      img-src *: 允许从任何源加载图片。
      script-src 'self': 允许从同一源加载脚本。
      style-src 'self': 允许从同一源加载样式表。
    */

    mainWindow.maximize();
    // console.log('mainUrl ======================> ', mainUrl)
    mainWindow.loadURL(mainUrl);

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
      // Dereference the window object, usually you would store windows
      // in an array if your app supports multi windows, this is the time
      // when you should delete the corresponding element.
      const name = 'PepReader';
      const exeDir = path.join(cfg.dirs.appPath, name);
      const exePath = path.join(exeDir, `${name}.exe`);
      util.killByPath(exePath);
      mainWindow = null;
    });

    mainWindow.once('ready-to-show', () => {
      mainWindow.show();
    });
    const showDevTools = process.argv && process.argv.includes('openDevTools');
    if (isDevelopment || __dev || showDevTools) {
      // mainWindow.webContents.openDevTools();
    }
  }

  return mainWindow;
}
